package app.controllers;

import app.models.Convenio;
import app.services.ConvenioService;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;

@Resource
public class ConvenioController {

	private final Result result;
	private final ConvenioService service;
	private final Validator validator;
	
	
	public ConvenioController(Result result, 
	Validator validator, ConvenioService service) {
		
		this.result = result;
		this.service = service;
		this.validator = validator;
	}
	
	@Get("/convenios")
	public void index() {
		this.result.include("convenioList",service.findAll());
		this.result.include("lastConvenioList",service.findLastConvenios());
	}

	@Get("/convenios/new")
	public void form() {
	}
	
	@Post("/convenios/save")
	public void create(Convenio convenio) {
		for(Convenio c: service.findAll()){
			if( (c.getNumero() == convenio.getNumero()) && c.getId() != convenio.getId() ){
				validator.add(new ValidationMessage("Convenio já cadastrado", "erro"));
			}
		}
		
		validator.validate(convenio);
		
		validator.onErrorForwardTo(this).form();
		service.create(convenio);
		
		this.result.forwardTo(this).index();
	}
	
	@Get("/convenios/{id}/edit")
	public void edit(Long id) {
		this.result.include("convenio", service.find(id));
	}
	
	@Post("/convenios/update")
	public void update(Convenio convenio) {
		for(Convenio c: service.findAll()){
			if( (c.getNumero() == convenio.getNumero()) && c.getId() != convenio.getId() ){
				validator.add(new ValidationMessage("Convenio já cadastrado", "erro"));
			}
		}
		
		validator.validate(convenio);
		
		validator.onErrorRedirectTo(this).edit(convenio.getId());
		service.update(convenio);
		
		this.result.redirectTo(this).index();
	}
	
}